package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.Random;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.ViteaQuery;
import com.ruoyi.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IBywViteaService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 简历中心库Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-09
 */
@Service
public class BywViteaServiceImpl implements IBywViteaService 
{
    @Autowired
    private BywViteaMapper bywViteaMapper;

    @Autowired
    private BywStageMapper stageMapper;

    @Autowired
    private BywEmployeeMapper employeeMapper;

    @Autowired
    private BywViteaOwnershipRelationMapper viteaOwnershipRelationMapper;

    @Autowired
    private BywUserHaveTiktokUserMapper userHaveTiktokUserMapper;

    @Autowired
    private BywUserVitaeInfoServiceImpl userVitaeInfoServiceImpl;

    @Autowired
    private BywTiktokUserServiceImpl bywTiktokUserService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询简历中心库
     * 
     * @param userPhone 简历中心库主键
     * @return 简历中心库
     */
    @Override
    public BywVitea selectBywViteaByUserPhone(String userPhone)
    {
        return bywViteaMapper.selectBywViteaByUserPhone(userPhone);
    }

    /**
     * 查询简历中心库列表
     * 
     * @param bywVitea 简历中心库
     * @return 简历中心库
     */
    @Override
    public List<BywVitea> selectBywViteaList(BywVitea bywVitea)
    {
        return bywViteaMapper.selectBywViteaList(bywVitea);
    }

    @Override
    public List<BywVitea> selecTiktokUserList(ViteaQuery viteaQuery)
    {
        return bywViteaMapper.selecTiktokUserList(viteaQuery);
    }

    @Override
    public List<String> selecUserPhoneList(ViteaQuery viteaQuery)
    {
        return bywViteaMapper.selecUserPhoneList(viteaQuery);
    }

    @Override
    public List<BywVitea> selecTiktokUserListByPhone(String[] userPhones)
    {
        return bywViteaMapper.selecTiktokUserListByPhone(userPhones);
    }

    /**
     * 新增简历中心库
     * 
     * @param bywVitea 简历中心库
     * @return 结果
     */
    @Override
    public int insertBywVitea(BywVitea bywVitea)
    {
        bywVitea.setCreateTime(DateUtils.getNowDate());
        return bywViteaMapper.insertBywVitea(bywVitea);
    }

    /**
     * 修改简历中心库
     * 
     * @param bywVitea 简历中心库
     * @return 结果
     */
    @Override
    public int updateBywVitea(BywVitea bywVitea)
    {
        bywVitea.setUpdateTime(DateUtils.getNowDate());
        return bywViteaMapper.updateBywVitea(bywVitea);
    }
    /**
     * 批量删除简历中心库
     * 
     * @param userPhones 需要删除的简历中心库主键
     * @return 结果
     */
    @Override
    public int deleteBywViteaByUserPhones(String[] userPhones)
    {
        return bywViteaMapper.deleteBywViteaByUserPhones(userPhones);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlock(Long sysUserId, String userPhone, BywVitea bywVitea) {
        // 4.解锁简历
        int num = bywViteaMapper.unlockVitea(userPhone);
        if (num <= 0){
            throw new RuntimeException("解锁失败");
        }
        // 5.客户的简历包 -1
        int i = userVitaeInfoServiceImpl.decreaseVitaeOne(sysUserId);
        if (i <= 0){
            throw new RuntimeException("扣除简历包失败");
        }
        BywVitea bywViteaUpdate = new BywVitea();
        bywViteaUpdate.setUserPhone(userPhone);
        if (StringUtils.isEmpty(bywVitea.getUnlockedUserId())){
            bywViteaUpdate.setUnlockedUserId(","+ sysUserId+",");
        } else {
            bywViteaUpdate.setUnlockedUserId(bywVitea.getUnlockedUserId() +","+ sysUserId+",");
        }

        bywViteaMapper.updateBywVitea(bywViteaUpdate);

        // 6.查到当前简历是谁推荐的，随机一个直接加1
        BywViteaOwnershipRelation bywViteaOwnershipRelationQuery = new BywViteaOwnershipRelation();
        bywViteaOwnershipRelationQuery.setViteaPhone(userPhone);
        bywViteaOwnershipRelationQuery.setState(0);
        List<BywViteaOwnershipRelation> bywViteaOwnershipRelations = viteaOwnershipRelationMapper.selectBywViteaOwnershipRelationList(bywViteaOwnershipRelationQuery);
        if (!CollectionUtils.isEmpty(bywViteaOwnershipRelations)){
            Random random = new Random();
            int randomIndex = random.nextInt(bywViteaOwnershipRelations.size());
            BywViteaOwnershipRelation bywViteaOwnershipRelation = bywViteaOwnershipRelations.get(randomIndex);
            // 达人
            if (bywViteaOwnershipRelation.getType() == 0){
                BywStage bywStage = stageMapper.selectBywStageByStageId(bywViteaOwnershipRelation.getUserId());
                if (bywStage == null){
                    logger.warn("简历可结算关系，达人不存在：id:{}, 达人id:{}", bywViteaOwnershipRelation.getId(), bywViteaOwnershipRelation.getUserId());
                } else {
                    int i1 = stageMapper.incrementVitea(bywStage);
                    if (i1 <=0 ){
                        throw new RuntimeException("达人简历数增加失败");
                    }
                }
            } else {
                BywEmployee bywEmployee = employeeMapper.selectBywEmployeeById(bywViteaOwnershipRelation.getUserId());
                if (bywEmployee == null){
                    logger.warn("简历可结算关系，员工不存在：id:{}, 员工id:{}", bywViteaOwnershipRelation.getId(), bywViteaOwnershipRelation.getUserId());
                } else {
                    int i1 = employeeMapper.incrementVitea(bywEmployee);
                    if (i1 <=0 ){
                        throw new RuntimeException("员工简历数增加失败");
                    }
                }
            }
            bywViteaOwnershipRelation.setState(1);
            bywViteaOwnershipRelation.setSettlementTime(DateUtils.getNowDate());
            viteaOwnershipRelationMapper.updateBywViteaOwnershipRelation(bywViteaOwnershipRelation);
        } else {
            logger.warn("简历可结算关系为空不结算：userId:{},viteaPhone:{}", sysUserId, userPhone);
        }

        BywUserHaveTiktokUser userHaveTiktokUser = new BywUserHaveTiktokUser();
        BeanUtils.copyProperties(bywVitea, userHaveTiktokUser);
        userHaveTiktokUser.setUserId(sysUserId);
        userHaveTiktokUser.setUnlockTime(DateUtils.getNowDate());
        userHaveTiktokUser.setTreatmentState(0);
        userHaveTiktokUser.setCreateTime(DateUtils.getNowDate());
        userHaveTiktokUser.setUpdateTime(userHaveTiktokUser.getUpdateTime());

        BywTiktokUser bywTiktokUser = bywTiktokUserService.selectBywTiktokUserByTiktokPhone(bywVitea.getUserPhone());
        if (bywTiktokUser != null){
            userHaveTiktokUser.setTiktokOpenId(bywTiktokUser.getTiktokOpenId());
            userHaveTiktokUser.setTiktokNickName(bywTiktokUser.getTiktokNickName());
        }
        userHaveTiktokUserMapper.insertBywUserHaveTiktokUser(userHaveTiktokUser);
    }

    /**
     * 删除简历中心库信息
     * 
     * @param userPhone 简历中心库主键
     * @return 结果
     */
    @Override
    public int deleteBywViteaByUserPhone(String userPhone)
    {
        return bywViteaMapper.deleteBywViteaByUserPhone(userPhone);
    }
}
